<script setup lang="ts">
import { ref } from 'vue'
import { useTodosStore } from '../stores/todos'
import { useSettingStore } from '../stores/setting'
import { useFilterTodosStore } from '../stores/filterTodos'
import DatePickerPopup from './DatePickerPopup.vue'
import CustLabel from './CustLabel.vue'

const todosStore = useTodosStore()
const filterTodosStore = useFilterTodosStore()
const settingStore = useSettingStore()
const popupRef = ref<{ open: () => void, close: () => void }>()

// 定义关闭事件
const emit = defineEmits(['close-popup'])

// 打开弹窗
const openPopup = () => {
  // 初始化本地筛选条件，从store获取当前值
  filterOptions.value = {
    status: filterTodosStore.filterOptions.status,
    labels: [...filterTodosStore.filterOptions.labels],
    timeRange: filterTodosStore.filterOptions.timeRange,
    keyword: filterTodosStore.filterOptions.keyword
  }
  popupRef.value?.open()
}

// 遮罩层点击事件处理
const onMaskClick = () => {
  closePopup()
}

// 日期选择器弹窗引用
const datePickerPopupRef = ref()

// 打开日期选择弹窗
const openDatePicker = () => {
  datePickerPopupRef.value?.openDatePicker(filterOptions.value.timeRange)
}

// 确认日期范围
const onDateRangeConfirm = (dateRange: [string, string]) => {
  filterOptions.value.timeRange = dateRange
}

// 格式化日期范围显示
const formatDateRange = (range: any) => {
  if (!range || range.length !== 2) {
    return '选择时间范围'
  }
  return `${range[0]} 至 ${range[1]}`
}

// 关闭弹窗
const closePopup = () => {
  emit('close-popup')
  // 触发关闭事件
  popupRef.value?.close()
}

// 是否展开标签选择下拉框
const showAddLabelSelection = ref(false)

// 切换添加标签选择下拉框
const toggleAddLabelSelection = () => {
  showAddLabelSelection.value = !showAddLabelSelection.value
}

// 切换标签选择状态
const toggleLabelSelection = (label: Label) => {
  // 查找todosStore中对应name的完整label对象
  const fullLabel = settingStore.allLabels.find(item => item.name === label.name)
  if (fullLabel) {
    const index = filterOptions.value.labels.findIndex(item => item.name === label.name)
    if (index > -1) {
      filterOptions.value.labels.splice(index, 1)
    } else {
      filterOptions.value.labels.push({ ...fullLabel })
    }
  }
}

// 删除标签
const removeLabel = (label: Label) => {
  const index = filterOptions.value.labels.findIndex(item => item.name === label.name)
  if (index > -1) {
    filterOptions.value.labels.splice(index, 1)
  }
}

// 当前筛选条件
const filterOptions = ref<FilterOptions>({
  status: 'all',
  labels: [],
  timeRange: null,
  keyword: ''
})

// 应用筛选条件
const applyFilters = () => {
  // 将筛选条件同步到store
  filterTodosStore.setFilterOptions({
    status: filterOptions.value.status,
    labels: filterOptions.value.labels,
    timeRange: filterOptions.value.timeRange,
    keyword: filterOptions.value.keyword
  })
  closePopup()
}

// 重置所有筛选条件
const resetFilters = () => {
  // 重置筛选条件
  filterOptions.value = {
    status: 'all',
    labels: [],
    timeRange: null,
    keyword: ''
  }
}

// 导出方法供父组件调用
defineExpose({
  openPopup,
  closePopup
})
</script>

<template>
  <!-- 底部筛选弹窗 -->
  <uni-popup ref="popupRef" type="bottom" :mask-click="true" background-color="#fff" border-radius="20rpx 20rpx 0 0" @close="closePopup" @mask-click="onMaskClick">
    <view class="filter-popup-container">
      <!-- 关闭按钮 -->
      <view class="popup-close-btn" @click="closePopup">
        <image src="../static/icons/delete-small.png" />
      </view>
      <view class="filter-content">
        <!-- 状态筛选 -->
        <view class="filter-section">
          <text class="section-title">筛选状态</text>
          <view class="filter-options">
            <view 
              class="filter-option" 
              :class="{ active: filterOptions.status === 'all' }"
              @click="filterOptions.status = 'all'">
              全部
            </view>
            <view 
              class="filter-option" 
              :class="{ active: filterOptions.status === 'doing' }"
              @click="filterOptions.status = 'doing'">
              进行中
            </view>
            <view 
              class="filter-option" 
              :class="{ active: filterOptions.status === 'done' }"
              @click="filterOptions.status = 'done'">
              已完成
            </view>
          </view>
        </view>

        <!-- 时间范围筛选 -->
        <view class="filter-section">
          <text class="section-title">时间范围</text>
          <view class="time-range-picker">
            <!-- 日期选择器弹窗组件 -->
            <DatePickerPopup
              ref="datePickerPopupRef"
              @confirm="onDateRangeConfirm"
            >
              <template #default>
                <view class="date-range-display" @click="openDatePicker">
                  <text v-if="!filterOptions.timeRange" class="placeholder">选择时间范围</text>
                  <text v-else class="date-text">{{ formatDateRange(filterOptions.timeRange) }}</text>
                </view>
              </template>
            </DatePickerPopup>
          </view>
        </view>

        <!-- 标签筛选 -->
        <view class="filter-section">
          <text class="section-title">筛选标签</text>
          <view class="labels-container" v-if="filterOptions.labels.length" @click="toggleAddLabelSelection">
            <CustLabel v-for="label in filterOptions.labels" :key="label.name" :label="label" type="deleteable" @delete="removeLabel(label)" />
          </view>
          <view class="labels-container" v-else @click="toggleAddLabelSelection">
            <view class="add-filter-label-btn placeholder">{{ showAddLabelSelection ? '可选择多个标签' : '添加标签' }}</view>
          </view>
        </view>

        <!-- 标签选择下拉框 -->
        <view class="filter-section" v-if="showAddLabelSelection">
          <!-- 所有标签列表 -->
          <view class="all-labels-list" v-if="settingStore.allLabels.length">
            <CustLabel
              v-for="label in settingStore.allLabels"
              :key="label.name"
              :label="label"
              type="primary"
              @click="toggleLabelSelection(label)"
            />
          </view>
          <!-- 暂无标签提示 -->
          <view class="no-labels-msg" v-else>
            暂无标签，可在个人设置中添加标签
          </view>
        </view>

        <!-- 关键词筛选 -->
        <view class="filter-section">
          <text class="section-title">关键词</text>
          <view class="search-input-container">
            <input
              v-model="filterOptions.keyword"
              maxlength="15"
              class="uni-input"
              placeholder="请输入关键词"
              placeholder-style="color: #999; font-weight: nomal;"
            />
          </view>
        </view>
      </view>

      <!-- 底部操作按钮 -->
      <view class="popup-footer">
        <button class="reset-btn" @click="resetFilters">重置</button>
        <button class="apply-btn" @click="applyFilters">确定</button>
      </view>
    </view>
  </uni-popup>
</template>

<style scoped lang="scss">
.filter-popup-container {
  width: 100%;
  position: relative;

  .popup-close-btn {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
    width: 45rpx;
    height: 45rpx;
    z-index: 10;
    
    image {
      width: 100%;
      height: 100%;
    }
  }

  .filter-content {
    padding: 30rpx;
    overflow-y: auto;
    max-height: 50vh;

    .placeholder {
      color: #999;
      font-size: 28rpx;
    }

    .filter-section {
      margin-bottom: 40rpx;

      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 20rpx;
        display: block;
      }

      .filter-options {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
        color: $uni-base-color;

        .filter-option {
          padding: 15rpx 30rpx;
          background-color: #f5f5f5;
          border-radius: 20rpx;
          font-size: 28rpx;

          &.active {
            background-color: #339ca8;
            color: #fff;
          }
        }
      }

      .time-range-picker {
        .date-range-display {
          height: 80rpx;
          background-color: #f5f5f5;
          border-radius: 10rpx;
          border: 1rpx solid #ddd;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 30rpx;
          position: relative;
          cursor: pointer;
          
          .date-text {
            color: #333;
            font-size: 28rpx;
          }
        }
      }

      .labels-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;
        gap: 20rpx;
        padding: 20rpx 30rpx;
        background-color: #f5f5f5;
        border: 1rpx solid #ddd;
        border-radius: 10rpx;
        min-height: 55rpx;
      }

      .all-labels-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        gap: 20rpx;
      }

      .search-input-container {
        padding: 20rpx 30rpx;
        background-color: #f5f5f5;
        border: 1rpx solid #ddd;
        border-radius: 10rpx;
        
        .search-input {
          border: none;
          padding: 0;
          font-size: 28rpx;
        }
        
        .search-input::placeholder {
          color: #999;
        }
      }
    }
  }

  .popup-footer {
    display: flex;
    gap: 30rpx;
    padding: 20rpx 30rpx;
    border-top: 1rpx solid #eee;

    .reset-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #f5f5f5;
      color: #666;
      font-size: 32rpx;
    }

    .apply-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #339ca8;
      color: #fff;
      font-size: 32rpx;
    }
  }
}
</style>